package com.cw.utils.web.sensitive;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 陈伟
 * @Date: 2022/09/26 18:13
 * @Description:
 * @Version s1.0
 **/
public class SensitiveUtil {
    //从api项目的配置文件获取当前环境标识
//    private static String SYS_UNIQUE_KEY = SystemConstantUtil.getInstance().readCommonProperties().getSysUniqueKey();

    private static SensitiveWordInit sensitiveWordInit = new SensitiveWordInit();

    public static LoadingCache<String, Map> cache = Caffeine.newBuilder()
            .maximumSize(2_000)
            .initialCapacity(200)//初始化大小
            .expireAfterWrite(30, TimeUnit.MINUTES)//30分钟加载一次
            .build(sensitive->getSensitiveWordMap(sensitive));

    private static Map getSensitiveWordMap(String sensitive){
        Map map = new HashMap();
//        if(SysUniqueKeyEnum.XYYH_122.getCode().equals(SYS_UNIQUE_KEY) || SysUniqueKeyEnum.ZHUI_SHENG_CHAN_105.getCode().equals(SYS_UNIQUE_KEY)){
            String filePath = "/sltas_system/sensitive/test.txt";
            map = sensitiveWordInit.initKeyWord(filePath);
//        }
        return map;
    }

    public static boolean checkSensitiveWord(String value){
        boolean flag = false;
        if(StringUtils.isBlank(value)){
            return false;
        }
//        if(SysUniqueKeyEnum.XYYH_122.getCode().equals(SYS_UNIQUE_KEY) || SysUniqueKeyEnum.ZHUI_SHENG_CHAN_105.getCode().equals(SYS_UNIQUE_KEY)){
            Map result = cache.get("sensitive");
            if(result==null || result.size()==0){
                return false;
            }
            SensitivewordFilter sensitivewordFilter = new SensitivewordFilter();
            //flag为true包含敏感词
            flag = sensitivewordFilter.isContaintSensitiveWord(value,1,result);
//        }
        return flag;
    }

    public static Set<String> getSensitiveWord(String value){
        if(StringUtils.isBlank(value)){
            return new HashSet();
        }
        Map result = cache.get("sensitive");
        if(result==null || result.size()==0){
            return new HashSet();
        }
        SensitivewordFilter sensitivewordFilter = new SensitivewordFilter();
        //flag为true包含敏感词
        Set<String> set = sensitivewordFilter.getSensitiveWord(value,1,result);
        return set;
    }
}